<?php
/**
 * @author phutp@younetco.com
 */
class Core_Util
{ 
	public static function redirect($url) 
	{
		header("Location: $url");
	}
	
	public static function parentRedirect($url) 
	{
		echo "<script language='javascript'>top.location.href='" . $url . "'</script>";
	}
	
	public static function isFacebookRequest()
	{
		$is_fb_request = false;

		if($_SERVER['HTTP_USER_AGENT'] == "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)")
		{
			$is_fb_request = true;
		}

		return $is_fb_request;
	}
    /**
     * Detect http user agent
     * @return boolean
     */
    public static function isSocialNetworksRequest() 
    {        
        $is_social_network = FALSE;
        file_put_contents('log.txt', $_SERVER['HTTP_USER_AGENT'].PHP_EOL, FILE_APPEND);
        switch ($_SERVER['HTTP_USER_AGENT']) 
        {
            case 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)':
                // Facebook
                $is_social_network = TRUE;
                break;
            case 'Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20110814 Firefox/6.0':
                // Google
                $is_social_network = TRUE;
                break;
            case 'LinkedInBot/1.0 (compatible; Mozilla/5.0; Jakarta Commons-HttpClient/3.1 +http://www.linkedin.com)':
                $is_social_network = TRUE;
                break;
            default :
                $is_social_network = FALSE;
        }
        return $is_social_network;
    }


    const VIEW_STATE_MANAGE = 'manage_view_state';
	const VIEW_STATE_ENTRY	= 'entry_view_state';
	
	const LATEST_MGS_ID		= 'latest_mgs';
	const THANK_YOU_MSG		= 'thank_you_msg';
	/**
	 *
	 * @param string $mg 
	 */
	public static function setLatestMessage($mg, $key = null)
	{
		$session = Zend_Registry::get('session');
		if(empty($key))
		{
			$session->{self::LATEST_MGS_ID} = $mg;
		}
		else
		{
			$session->{$key} = $mg;
		}
	}

	/**
	 *
	 * @param boolean $clear
	 * @return string 
	 */
	public static function getLatestMessage($key = null, $clear = true)
	{
		$session = Zend_Registry::get('session');
		
		if(empty($key))
		{
			$key = self::LATEST_MGS_ID;
		}
		
		$value	= $session->{$key};

		if( $clear )
		{
			$session->{$key} = NULL;
		}
		
		return $value;
	}
	
	/**
	 * Check is there any message exist in session
	 * @return boolean 
	 */
	public static function hasMessage($key = null)
	{
		$session = Zend_Registry::get('session');
		
		if(empty($key))
		{
			$key = self::LATEST_MGS_ID;
		}
		
		if(!empty($session->{$key}))
		{
			if(trim($session->{$key}) != '')
			{
				return true;
			}
		}
			
		return false;
	}
	
	/**
	 * Remove new line characters, and escape single-quoted
	 * @param string $input
	 * @return string 
	 */
	public static function escapeForJS($input)
	{
		$order = array("\r\n", "\n", "\r");
		$output =  str_replace($order, '', $input);
		$output =  str_replace("'", "\'", $output);
		return $output;
	}
	
	public static function escapeForJs2($text)
	{
		$value = str_replace("\r\n", '\n', htmlspecialchars($text));
		return str_replace("\n", '\n', $value);
	}
		
	/**
	 *
	 * @return Zend_Cache_Frontend_Page
	 */
	public static function getPageCache()
	{
		static $cache = null;
		if( !($cache instanceof Zend_Cache_Frontend_Page) )
		{
			$cache = Zend_Cache::factory(
				'Page',
				'File',
				array(
					'options'		=> array(
						
					)
				),
				array(
					'cache_dir'		=> APPLICATION_PATH.'/../public/cache/file/'
				)
			);
		}
		return $cache;
	}
	
	/**
	 *
	 * @return Zend_Cache_Frontend_Output
	 */
	public static function getOuputCache()
	{
		static $cache = null;
		if( !($cache instanceof Zend_Cache_Frontend_Output) )
		{
			$cache = Zend_Cache::factory(
				'Output',
				'File',
				array(
					'options'		=> array(
						
					)
				),
				array(
					'cache_dir'		=> APPLICATION_PATH.'/../public/cache/file/'
				)
			);
		}
		return $cache;
	}
	
	/**
	 *
	 * @return Zend_Cache_Frontend_Output
	 */
	public static function getFileCache()
	{
		static $cache = null;
		if( !($cache instanceof Zend_Cache_Frontend_Output) )
		{
			$cache = Zend_Cache::factory(
				'Core',
				'File',
				array(
					'automatic_serialization' => true,
				),
				array(
					'cache_dir'		=> APPLICATION_PATH.'/../public/cache/file/'
				)
			);
		}
		return $cache;
	}
	
	public static function createThumbnail($source, $thumbnail, $size)
	{		
		$storage = Zend_Registry::get('storage');
		if ($storage instanceof YouNet_Storage_S3)
		{
			$thumbnail_local = INDEX_PATH . '/../..' . $thumbnail;
			$storage->copyToLocal($source, $thumbnail_local);
			self::cropThumbnail($thumbnail_local,$size); 
			$storage->put($thumbnail, file_get_contents($thumbnail_local)); 
		}
		else
		{
			copy($source, $thumbnail);
			self::cropThumbnail($thumbnail,$size);
		}
	}
	
	public static function cropThumbnail($thumbnail,$size)
	{
		list($width, $height) = getimagesize($thumbnail);
		$min = min(array($width, $height));
		
		$cropWidth = $cropHeight = $size;
		Core_ImageUtil::crop($thumbnail, $cropWidth, $cropHeight, 0, 0, $min, $min);
	}
    public static function getTimeAt0($time)
	{
		return strtotime(Date('Y-m-d', $time));
	}
    public static function getBitlyUrl($long_url)
	{
		$client = new Zend_Http_Client(BITLY_HOST);
		$client->setParameterGet(array(
			'longUrl'	=> $long_url,
			'login'		=> BITLY_USERNAME,
			'apiKey'	=> BITLY_API_KEY
		));
		$response = $client->request();

		$shortUrl = '';
		if( $response->isSuccessful() )
		{
           
			$response = Zend_Json::decode($response->getBody());
			if($response['status_code'] == 200)
			{
				$shortUrl = $response['data']['url'];
			}
		}
        
		return $shortUrl;
	}
    
    public static function array_random_assoc($arr, $num = 1) {
        $keys = array_keys($arr);
        shuffle($keys);

        $r = array();
        for ($i = 0; $i < $num; $i++) {
            $r[$keys[$i]] = $arr[$keys[$i]];
        }
        return $r;
    }
    
    public static function convertDateFormatFromWeb2Db($date_string)
    {
        $format_to      = sprintf('%s-%s-%s', Zend_Date::YEAR, Zend_Date::MONTH, Zend_Date::DAY);
        $format_from    = sprintf('%s/%s/%s', Zend_Date::DAY, Zend_Date::MONTH, Zend_Date::YEAR);
        return self::convertDateFromat($date_string, $format_from, $format_to);
    }
    public static function convertDateFormatFromDb2Web($date_string)
    {
        $format_to      = sprintf('%s/%s/%s', Zend_Date::DAY, Zend_Date::MONTH, Zend_Date::YEAR);
        $format_from    = sprintf('%s-%s-%s', Zend_Date::YEAR, Zend_Date::MONTH, Zend_Date::DAY);
        return self::convertDateFromat($date_string, $format_from, $format_to);
    }
    public static function convertDateFromat($date_string, $format_from, $format_to)
    {
        $date = new Zend_Date($date_string,$format_from);
        return $date->toString($format_to);
    }
}